package lib

import "github.com/xanzy/go-gitlab"

type GitlabProject struct {
	Id        uint   `json:"id"`
	ProjectId int    `json:"project_id"`
	Name      string `json:"name"`
	NameSpace string `json:"name_space"`
	HttpUrl   string `json:"http_url"`
	SshUrl    string `json:"ssh_url"`
}

func GetAllProjects(token, baseUrl string) ([]*GitlabProject, error) {
	var gitlabProjects []*GitlabProject
	gitlabClient, err := gitlab.NewClient(token, gitlab.WithBaseURL(baseUrl))
	if err != nil {
		return gitlabProjects, err
	}
	options := gitlab.ListOptions{
		PerPage: 100,
		Page:    1,
	}

	for {
		projects, resp, err := gitlabClient.Projects.ListProjects(&gitlab.ListProjectsOptions{
			ListOptions: options,
		}, nil)
		if err != nil {
			return gitlabProjects, err
		}
		// 将仓库添加到存储切片
		for _, project := range projects {
			gitlabProjects = append(gitlabProjects, &GitlabProject{
				ProjectId: project.ID,
				Name:      project.Name,
				NameSpace: project.Namespace.Name,
				HttpUrl:   project.HTTPURLToRepo,
				SshUrl:    project.SSHURLToRepo,
			})
		}

		// 检查是否还有更多仓库需要获取
		if resp.CurrentPage >= resp.TotalPages {
			break
		}

		// 更新分页选项
		options.Page = resp.NextPage
	}
	return gitlabProjects, nil
}
